<template>
  <div class="app-container">
    <div class="topSearch">
      <el-row>
        <el-input
          v-model="searchCriteria.name"
          clearable
          maxlength="50"
          placeholder="Name"
        />
        <el-input
          v-model="searchCriteria.suffix"
          maxlength="50"
          clearable
          placeholder="Name Suffix"
        />
        <el-button type="primary" @click="searchData()">Search</el-button>
        <el-button
          type="primary"
          @click="showDialog('add')"
        >Add Image</el-button>
      </el-row>
    </div>
    <div class="imgWrap">
      <div v-if="imgList.length" class="imgList">
        <div
          v-for="item in imgList"
          :key="item.id"
          :class="['imgBox', item.id === activeId ? 'active' : '']"
        >
          <el-image
            lazy
            :src="imgPrefix + item.uri + imgSuffix"
            fit="cover"
            @click="viewInfo(item)"
          />
        </div>
      </div>
      <div v-else class="noDataTip">No Imgaes</div>
      <div class="imgInfo">
        <div v-if="viewItem">
          <p class="title">Image Info</p>
          <el-image
            :src="imgPrefix + viewItem.uri + imgSuffix"
            @click="toProview(imgPrefix + viewItem.uri)"
          />
          <p class="name">{{ viewItem.storeName || viewItem.storeId }}</p>
          <p class="uri">{{ viewItem.uri }}</p>
          <p class="time">{{ viewItem.createTime }}</p>
          <el-button
            v-preventReClick
            type="text"
            size="small"
            @click="toProview(imgPrefix + viewItem.uri)"
          >Preview</el-button>
          <el-button
            v-preventReClick
            type="text"
            size="small"
            @click="deleteItem(viewItem.id)"
          >Delete</el-button>
        </div>
      </div>
    </div>
    <el-pagination
      v-if="imgList.length"
      id="btmPagination"
      :class="{ open: sidebar }"
      :current-page="currentPage"
      :page-sizes="[10, 30, 50, 100, 200]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <!-- 图片预览 -->
    <proview-img v-if="proviewUrl" :src="proviewUrl" @close="closeProview" />

    <el-dialog
      title="Add image"
      :visible.sync="dialogFormVisible"
      width="400px"
    >
      <el-form :label-width="formLabelWidth">
        <el-form-item label="Store Name">
          <el-select
            v-model="formParams.storeId"
            placeholder="please select the store"
          >
            <el-option
              v-for="item in storeOptions"
              :key="item.id"
              :label="storeTypeMap[item.type] + '-' + item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="Image">
          <el-upload
            action="void"
            accept="image/jpg,image/jpeg,image/png"
            :show-file-list="false"
            :before-upload="beforeUpload"
          >
            <img v-if="formParams.imageUrl" :src="formParams.imageUrl">
            <i v-else class="el-icon-plus uploader-icon" />
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">Cancel</el-button>
        <el-button
          v-preventReClick
          type="primary"
          @click="productImagesAdd(formParams.file)"
        >Confirm</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  productImagesPage,
  productImagesDelete,
  productImagesAdd
} from '@/api/product';
import { authorizedList } from '@/api/authorized';
import { postResult } from '@/utils/dataFormat';
import ProviewImg from '@/components/Proview/proviewImg';
export default {
  components: {
    ProviewImg
  },
  data() {
    return {
      imgList: [],
      searchCriteria: {},
      currentPage: 1,
      pageSize: 30,
      total: 0,
      activeId: 0,
      viewItem: null,
      proviewUrl: '',
      dialogFormVisible: false,
      formLabelWidth: '100px',
      storeTypeMap: {
        1: 'Shopify',
        2: 'Woocommerce'
      },
      storeOptions: [],
      formParams: {
        storeId: null,
        file: null,
        imageUrl: ''
      }
    };
  },
  computed: {
    sidebar() {
      return this.$store.state.app.sidebar.opened;
    }
  },
  mounted() {
    this.init();
    this.authorizedList();
  },
  methods: {
    init() {
      productImagesPage({
        ...this.searchCriteria,
        pageNo: this.currentPage,
        pageSize: this.pageSize,
        storeId: -1
      }).then((res) => {
        this.imgList = res.data.data;
        this.total = res.data.totalCount;
      });
    },
    authorizedList() {
      authorizedList({
        storeType: 'VIRTUAL'
      }).then((res) => {
        const data = res.data.filter((item) => item.type !== 4);
        this.storeOptions = data;
      });
    },
    searchData() {
      this.currentPage = 1;
      this.init();
    },
    viewInfo(item) {
      this.activeId = item.id;
      this.viewItem = item;
    },
    deleteItem(id) {
      productImagesDelete(id).then((res) => {
        postResult(res, this.$message, this.init);
        if (res.code === 200) {
          this.viewItem = null;
        }
      });
    },
    showDialog() {
      this.formParams = {
        storeId: null,
        file: null,
        imageUrl: ''
      };
      this.dialogFormVisible = true;
    },
    beforeUpload(file) {
      this.formParams.file = file;
      this.formParams.imageUrl = window.URL.createObjectURL(file);
    },
    productImagesAdd(file) {
      if (!file || !this.formParams.storeId) {
        this.$message.warning('The information submitted is incomplete.');
        return;
      }
      if (file.name.length > this.nameLength) {
        file.name = file.name.substring(file.name.length - this.nameLength);
      }
      const params = {
        fileSize: file.size,
        storeId: this.formParams.storeId,
        categoryId: 0,
        name: file.name
      };
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => {
        this.showImage = true;
        params.fileContent = reader.result;
        productImagesAdd(params).then((res) => {
          if (res.code === 200) {
            this.dialogFormVisible = false;
            this.formParams = {
              storeId: null,
              file: null,
              imageUrl: ''
            };
          }
          postResult(res, this.$message, this.init);
        });
      };
    },
    toProview(url) {
      // 预览图片
      this.proviewUrl = url;
    },
    closeProview() {
      // 关闭预览
      this.proviewUrl = '';
      document.querySelector('body').removeAttribute('style');
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.init();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.init();
    }
  }
};
</script>

<style scoped lang="scss">
@media screen and (max-width: 1400px) {
  .imgList {
    .imgBox {
      width: 12.5% !important;
    }
  }
}
@media screen and (max-width: 1000px) {
  .imgList {
    .imgBox {
      width: 16.6% !important;
    }
  }
}
@media screen and (max-width: 750px) {
  .imgList {
    .imgBox {
      width: 25% !important;
    }
  }
}
.imgWrap {
  display: flex;
  margin-bottom: 40px;
  .imgList {
    width: 0;
    flex: 1;
    border-right: 1px solid #acacac;
    .imgBox {
      float: left;
      position: relative;
      overflow: hidden;
      width: 10%;
      padding: 10px;
      &:before {
        content: '';
        display: block;
        margin-top: 100%;
      }
      .el-image {
        position: absolute;
        top: 10px;
        left: 10px;
        right: 10px;
        bottom: 10px;
        cursor: pointer;
        border: 1px dashed #ddd;
        transition: 0.3s;
      }
      &.active {
        .el-image {
          transform: scale(0.8);
          border: 1px solid #409eff;
        }
      }
    }
  }
  .noDataTip {
    width: 0;
    flex: 1;
    text-align: center;
    padding-top: 100px;
    color: #848484;
  }
  .imgInfo {
    width: 240px;
    height: 400px;
    margin-left: 20px;
    padding: 0 10px;
    background: #f3f3f3;
    .el-image {
      width: 150px;
      height: 150px;
      border: 1px solid #ddd;
      cursor: pointer;
    }
    .uri,
    .time {
      white-space: pre-wrap;
      color: #666;
      font-size: 14px;
      padding-top: 15px;
      word-break: break-all;
    }
    .name {
      padding-top: 15px;
    }
    .title {
      line-height: 40px;
      font-weight: 600;
      color: #333;
      font-size: 16px;
    }
  }
}

::v-deep .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  height: 100px;
  width: 100px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  .uploader-icon {
    font-size: 16px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }
  img {
    object-fit: cover;
    width: 100px;
    height: 100px;
  }
}
</style>
